package com.jt.www.admin.market.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jt.www.admin.market.service.InsidePerformanceService;
import com.jt.www.dao.mapper.market.InsidePerformanceMapper;
import com.jt.www.dao.mapper.registerCustomer.RegisterCustomerMapper;
import com.jt.www.domain.enums.common.IsDeletedEnum;
import com.jt.www.domain.enums.wxb.PerformanceSendStatusEnum;
import com.jt.www.domain.po.InsidePerformance;
import com.jt.www.domain.qo.InsidePerformanceQO;
import com.jt.www.domain.vo.PolicyDetailVO;
import com.jt.www.model.registerCustomer.RegisterCustomer;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.GenericResponse;
import com.jt.www.remote.ins.InsClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.List;

/**
 * 内部人员业绩
 * Created by shaoyn on 2020/07/21.
 */
@Service
public class InsidePerformanceServiceImpl implements InsidePerformanceService {

    public static final Logger log = LoggerFactory.getLogger(InsidePerformanceServiceImpl.class);

    @Autowired
    private InsidePerformanceMapper insidePerformanceMapper;
    @Autowired
    private InsClient insClient;
    @Autowired
    private RegisterCustomerMapper registerCustomerMapper;


    @Override
    public ResponseEntity<GenericListResponse<InsidePerformance>> queryInsidePerformance(InsidePerformanceQO insidePerformanceQO) {
        Long count = insidePerformanceMapper.selectInsidePerformanceListCount(insidePerformanceQO);
        if (null == count || count <= 0) {
            return GenericListResponse.listNoCount(null);
        }
        List<InsidePerformance> offlineOrderVos = insidePerformanceMapper.selectInsidePerformanceList(insidePerformanceQO);
        return GenericListResponse.listAndCount(offlineOrderVos, count);
    }

    @Override
    public InsidePerformance queryInsidePerformanceByPolicyNo(String policyNo) {
        return null;
    }

    @Override
    public int updateSendStatus(InsidePerformanceQO insidePerformanceQO, String sendStatus) {
        if (null == insidePerformanceQO
                || StringUtils.isEmpty(PerformanceSendStatusEnum.getDestByStatus(sendStatus))) {
            return 0;
        }
        return insidePerformanceMapper.updateSendStatus(insidePerformanceQO, sendStatus);
    }

    @Override
    public ResponseEntity<GenericResponse> updateInsidePerformanceManager(String ids) {
        String findCode = "updateInsidePerformanceManager_" + System.currentTimeMillis();
        List<InsidePerformance> list = Lists.newArrayList();
        if (StringUtils.isBlank(ids) || "-1".equals(ids)) {
            list = insidePerformanceMapper.selectAll();
        } else {
            for (String id : ids.split(",")) {
                InsidePerformance insidePerformance = insidePerformanceMapper.selectByPrimaryKey(Long.parseLong(id));
                if (null != insidePerformance) {
                    list.add(insidePerformance);
                }
            }
        }
        log.info("{} 查询结果个数 {}", findCode, list.size());
        for (InsidePerformance insidePerformance : list) {
            String detailFindCode = findCode + "_" + insidePerformance.getPolicyNo();
            try {
                GenericDataResponse<PolicyDetailVO> res = insClient.policyDetail(insidePerformance.getPolicyNo());
                log.info("{} 通过保单号查询保单信息 {}", detailFindCode, JSON.toJSONString(res));
                if (null != res && null != res.getData() && GenericDataResponse.CODE_OK.equals(res.getCode())) {
                    PolicyDetailVO policyDetailVO = res.getData();
                    String userCode = policyDetailVO.getHolder().getHolderCode();
                    if (StringUtils.isBlank(userCode)) {
                        log.info("{} 投保单号：{} 被推广人:userCode 为空，不做处理。", detailFindCode, policyDetailVO.getAppCode());
                    }
                    //获取该用户当前推广人
                    Weekend<RegisterCustomer> weekend = Weekend.of(RegisterCustomer.class);
                    WeekendCriteria<RegisterCustomer, Object> criteria = weekend.weekendCriteria();
                    criteria.andEqualTo(RegisterCustomer::getCustomerCode, userCode);
                    criteria.andEqualTo(RegisterCustomer::getIsDeleted, false);
                    List<RegisterCustomer> registerCustomers = registerCustomerMapper.selectByExample(weekend);
                    //校验推广人是否过期 且与保单记录的推广人是否是同一个人
                    if (CollectionUtils.isEmpty(registerCustomers)) {
                        log.info("{} 投保单号：{} 被推广人:userCode {}无推广人。将原有内部推广信息删除。", detailFindCode, policyDetailVO.getAppCode(), userCode);
                        InsidePerformance insidePerformance1 = new InsidePerformance();
                        insidePerformance1.setId(insidePerformance.getId());
                        insidePerformance1.setIsDeleted(IsDeletedEnum.IS.getValue());
                        insidePerformanceMapper.updateByPrimaryKeySelective(insidePerformance1);
                        continue;
                    }
                    RegisterCustomer registerCustomer = registerCustomers.get(0);
                    InsidePerformance insidePerformance1 = new InsidePerformance();
                    insidePerformance1.setId(insidePerformance.getId());
                    insidePerformance1.setManagerName(registerCustomer.getManagerName());
                    insidePerformance1.setManagerAccount(registerCustomer.getManagerAccount());
                    insidePerformance1.setBranchCode(registerCustomer.getBranchCode());
                    insidePerformance1.setBranchName(registerCustomer.getBranchName());
                    insidePerformanceMapper.updateByPrimaryKeySelective(insidePerformance1);
                }
            } catch (Exception e) {
                log.error("{} 通过保单号查询保单信息异常", detailFindCode);
            }
        }
        return GenericDataResponse.ok();
    }


}
